package it.okkam.longwell.ui.command;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.impl.PropertyImpl;
import com.hp.hpl.jena.rdf.model.impl.ResourceImpl;
import com.hp.hpl.jena.vocabulary.DC;

import de.fuberlin.wiwiss.ng4j.NamedGraph;
import de.fuberlin.wiwiss.ng4j.NamedGraphSet;
import de.fuberlin.wiwiss.ng4j.NamedGraphStatement;
import de.fuberlin.wiwiss.ng4j.Quad;
import de.fuberlin.wiwiss.ng4j.impl.NamedGraphSetImpl;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;

public class GetSourceCommand extends CommandBase {
	final static private Logger s_logger = Logger.getLogger(GetSourceCommand.class);
	
	/**
	 * @param injectionManager
	 */
	public GetSourceCommand(InjectionManager injectionManager) {
		super(injectionManager);
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage)
	 */
	public void execute(FlairMessage msg) throws ServletException {
		try {

			String pseudoURI = msg.m_query.getFirstParamValue("uri");
			String ont = msg.m_query.getFirstParamValue("ontology");
			String ontProp = "#"+msg.m_query.getFirstParamValue("ontProp");
			String value = msg.m_query.getFirstParamValue("value");
			String property = ont+ontProp;	
			if(value.contains("pseudoURI")){
				value=value.substring(value.indexOf("=")+1, value.length());
			}
			VelocityContext vcContext = createContext(msg);
			String sessionId = msg.m_profileID;
			
			Set<String> listGraphFind = new HashSet<String>();
			HashMap<String, Dataset> hash = SelectGraphsCommand.getGraphsByDataset(sessionId);
			String[] graphsSelectedList = ChangeModelCommand.getGraphsSelected("graphsSelected"+msg.m_profileID);
			String[] dataset = (String[]) msg.m_request.getSession().getAttribute(msg.m_request.getSession().getId());
			for(int i = 0 ; i<graphsSelectedList.length;i++){
				Dataset ds = hash.get(graphsSelectedList[i]);
				Model defaultModel = ds.getNamedModel("http://www.provincia.tn.it/bcc/resource/"+dataset[0]);
				Model model = ds.getNamedModel(graphsSelectedList[i]);
				Resource r = model.getResource(pseudoURI);								
				Statement statement = r.getProperty(model.getProperty(property));
				if(statement!=null){
				//if(statement!=null && statement.getObject().toString().equals(value)){
					Boolean find = model.contains(statement);
					if(find){					
						Property issued = new PropertyImpl("http://purl.org/dc/elements/1.1/issued");
						Property hasPart = new PropertyImpl("http://purl.org/dc/elements/1.1/hasPart");
						Resource uriFlow = new ResourceImpl(graphsSelectedList[i]);
						Iterator<Statement> stmtLabel = defaultModel.listStatements(uriFlow, issued,(RDFNode) null);
						Iterator<Statement> flow = defaultModel.listStatements(null, hasPart,(RDFNode) uriFlow);
						String title="";
						while(flow.hasNext()){
							Resource flowName = flow.next().getSubject();
							Iterator<Statement> titleStmt = defaultModel.listStatements(flowName, DC.title,(RDFNode) null);
							title=titleStmt.next().getObject().toString();
							//System.out.println(flowName);
						}
						//read label
						while(stmtLabel.hasNext()){
							String label = stmtLabel.next().getObject().toString();
							listGraphFind.add(title+" - "+label+"<br>");
						}
					}	
				}
			}
			vcContext.put("graphs", listGraphFind);
			msg.m_ve.mergeTemplate(
					"templates/commands/get-source.vt",
					vcContext,
					msg.m_response.getWriter());			
		} catch (Throwable e) {
			s_logger.error(e);
			e.printStackTrace();
		}
	}
}